var context = null; // 使用 wx.createContext 获取绘图上下文 context
var isButtonDown = false; //是否在绘制中
var arrx = []; //动作横坐标
var arry = []; //动作纵坐标
var arrz = []; //总做状态，标识按下到抬起的一个组合
var canvasw = 0; //画布宽度
var canvash = 0; //画布高度

var mod = '';//签名模式。qm：管理员、工程师设计签名；wx：接受维修者签名
var wxid = 0;//维修订单ID

var needyulan = true;
const app = getApp();

// pages/shouxieban/shouxieban.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    current: '1',
    //canvas宽高
    canvasw: 0,
    canvash: 0,
    //canvas生成的图片路径
    canvasimgsrc: "",
    yl: false, //预览
  },
  //画布初始化执行
  startCanvas: function() {
    var that = this;
    //创建canvas
    this.initCanvas();
    //获取系统信息
    wx.getSystemInfo({
      success: function(res) {
        canvasw = res.windowWidth - 0; //设备宽度
        canvash = canvasw * 0.5;
        that.setData({
          'canvasw': canvasw
        });
        that.setData({
          'canvash': canvash
        });
        //设置背景色
        context.rect(0, 0, canvasw, canvash);
        context.setFillStyle("#fff")
        context.fill() //设置填充
        context.draw() //开画

      }
    });

  },
  //初始化函数
  initCanvas: function() {
    // 使用 wx.createContext 获取绘图上下文 context
    context = wx.createCanvasContext('canvas');
    context.beginPath()
    context.setStrokeStyle('#000000');
    context.setLineWidth(2);
    context.setLineCap('round');
    context.setLineJoin('round');
  },
  //事件监听
  canvasIdErrorCallback: function(e) {
    console.error(e.detail.errMsg)
  },
  canvasStart: function(event) {
    isButtonDown = true;
    arrz.push(0);
    arrx.push(event.changedTouches[0].x);
    arry.push(event.changedTouches[0].y);

  },
  canvasMove: function(event) {
    if (isButtonDown) {
      arrz.push(1);
      arrx.push(event.changedTouches[0].x);
      arry.push(event.changedTouches[0].y);

    };

    for (var i = 0; i < arrx.length; i++) {
      if (arrz[i] == 0) {
        context.moveTo(arrx[i], arry[i])
      } else {
        context.lineTo(arrx[i], arry[i])
      };

    };




    context.clearRect(0, 0, canvasw, canvash);
    context.setStrokeStyle('#000000');
    context.setLineWidth(2);
    context.setLineCap('round');
    context.setLineJoin('round');
    context.stroke();

    context.draw(false);
  },
  canvasEnd: function(event) {
    isButtonDown = false;
    needyulan = true;
  },
  //清除画布
  cleardraw: function() {
    //清除画布
    arrx = [];
    arry = [];
    arrz = [];
    context.clearRect(0, 0, canvasw, canvash);
    context.draw(true);
    needyulan = true;
    this.setData({
      yl: false,
      canvasimgsrc: ""
    })
  },
  //提交签名内容
  setSign: function() {
    var that = this;
    if (arrx.length == 0) {
      wx.showModal({
        title: '提示',
        content: '签名内容不能为空！',
        showCancel: false
      });
      return false;
    };
    console.log("不是空的，canvas即将生成图片")
    //生成图片
    wx.canvasToTempFilePath({
      canvasId: 'canvas',
      fileType: 'png',
      quality: 1, //图片质量
      success: function(res) {
        console.log("canvas可以生成图片")
        console.log(res.tempFilePath, 'canvas图片地址');
        that.setData({
          canvasimgsrc: res.tempFilePath,
          yl: true
        })
        //code 比如上传操作
        needyulan = false;
      },
      fail: function() {
        console.log("canvas不可以生成图片")
        wx.showModal({
          title: '提示',
          content: '微信当前版本不支持，请更新到最新版本！',
          showCancel: false
        });
      },
      complete: function() {

      }
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options);
    mod = options.mode;
    wxid = options.id;
    //画布初始化执行
    this.startCanvas();
    wx.hideLoading();
  },
  onUnload() {
    mod = '';
    wxid = 0;
  },
  onChange(e) { //TabBar选项卡切换
    console.log('onChange', e)
    if (e.detail.key == '0') {
      wx.reLaunch({
        url: '/pages/index/canvas2?mode=' + mod + '&id=' + wxid
      })
    }
  },
  tijiaobtn: function(e) { //上传签名
    console.log(mod)
    if (needyulan) {
      wx.showModal({
        title: '提示',
        content: '请先点击预览按钮',
        showCancel: false
      });
      return false;
    } else {
      var uid = wx.getStorageSync('uid');
      var img = this.data.canvasimgsrc;
      var u = app.globalData.url + "qianming.php";
      var that=this;
      //上传
      wx.uploadFile({
        url: u, // 仅为示例，非真实的接口地址,比如：http://localhost/upload.php
        filePath: img,
        name: 'file',
        header: {
          'Content-Type': 'application/json'
        },
        formData: {
          uid: uid,
          zhuan: 0,
          mode: mod,
          id: wxid
        },
        success(res) {
          console.log(res.data);
          var r = JSON.parse(res.data);
          console.log(r);
          if (r.status == '1') {
            wx.showToast({
              title: '签名保存成功',
              icon: 'success',
              duration: 2000
            })
            setTimeout(function() {
              that.cleardraw();
              if (mod == 'qm') {
                wx.reLaunch({
                  url: '/pages/index/index'
                })
              } else {
                wx.reLaunch({
                  url: '/pages/wxxm/wxxm?d=[]&id=' + wxid
                })
              }
            }, 2000)
          } else {
            wx.showModal({
              title: '提示',
              content: res.data.msg,
              showCancel: false
            });
          }
        },
        fail(res) {
          console.log(res);
          wx.showModal({
            title: '提示',
            content: '失败，请重试',
            showCancel: false
          });
        }
      })

    }
  }
})